<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
    >

      <el-form-item label="图片" prop="cover">
        <el-upload
          class="avatar-uploader"
          :action="getUploadUrl()"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <img v-if="formData.cover" :src="formData.cover" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input v-model="formData.title" type="textarea" placeholder="请输入标题"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="摘要" prop="summary">
            <el-input v-model="formData.summary" type="textarea" placeholder="请输入摘要"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio
                  v-for="dict in getIntDictOptions(DICT_TYPE.MZT_STATUS)"
                  :key="dict.value"
                  :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="推荐" prop="recommend">
            <el-radio-group v-model="formData.recommend">
              <el-radio
                  v-for="dict in getIntDictOptions(DICT_TYPE.MZT_RECOMMEND)"
                  :key="dict.value"
                  :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="绑定分类" prop="categoryId">
            <el-select v-model="formData.categoryId" clearable placeholder="请选择分类" @change="onChangedCategory">
              <el-option
                  v-for="item in categoryOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="绑定标签" prop="tagIds">
            <el-select v-model="formData.tagIds" multiple placeholder="请选择标签">
              <el-option
                  v-for="item in tagOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="SEO标题" prop="seoTitle">
            <el-input v-model="formData.seoTitle" type="textarea" placeholder="请输入SEO标题"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="SEO关键词" prop="seoKeywords">
            <el-input v-model="formData.seoKeywords" type="textarea" placeholder="请输入SEO关键词"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="SEO描述" prop="seoDescription">
        <el-input v-model="formData.seoDescription" type="textarea" placeholder="请输入SEO描述"/>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <Editor v-model="formData.content" height="800px"/>
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {getIntDictOptions, DICT_TYPE} from '@/utils/dict'
import {ArticleApi, ArticleVO} from '@/api/mzt/article'
import {CategoryApi, CategoryVO} from '@/api/mzt/category'
import {TagApi, TagVO} from '@/api/mzt/tag'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

type FileTypes =
  | 'image/apng'
  | 'image/bmp'
  | 'image/gif'
  | 'image/jpeg'
  | 'image/pjpeg'
  | 'image/png'
  | 'image/svg+xml'
  | 'image/tiff'
  | 'image/webp'
  | 'image/x-icon'
/** 文章 表单 */
defineOptions({name: 'ArticleForm'})
// 分类选项
const categoryOptions = ref([])
// 标签选项
const tagOptions = ref([])
const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const getUploadUrl = () => {
  return import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/mzt/file/upload';
}
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: undefined,
  cover: undefined,
  summary: undefined,
  content: undefined,
  status: 0,
  recommend: 0,
  seoTitle: undefined,
  seoKeywords: undefined,
  seoDescription: undefined,
  categoryName: undefined,
  categoryId: undefined,
})
const formRules = reactive({
  title: [{required: true, message: '标题不能为空', trigger: 'blur'}],
  cover: [{required: true, message: '图片不能为空', trigger: 'blur'}],
  content: [{required: true, message: '内容不能为空', trigger: 'blur'}],
  status: [{required: true, message: '状态不能为空', trigger: 'blur'}],
  recommend: [{required: true, message: '推荐不能为空', trigger: 'blur'}],
  categoryId: [{required: true, message: '绑定分类不能为空', trigger: 'blur'}],
  tagIds: [{required: true, message: '绑定标签不能为空', trigger: 'blur'}],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  init();
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ArticleApi.getArticle(id)
    } finally {
      formLoading.value = false
    }
  }
}
const init = async () => {
  const category = await CategoryApi.getCategoryStatus({type:"TOP"})
  const tag=  await TagApi.getTagStatus({});
  categoryOptions.value =category;
  tagOptions.value=tag
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗
const onChangedCategory = (id?: number) => {
  if (id !== undefined) { // 确保传入的 id 是有效的
    const found = categoryOptions.value.find((v) => v.id === id);
    if (found) { // 检查 found 是否存在
      formData.value.categoryName = found.name; // 赋值
    } else {
      formData.value.categoryName = ''; // 清空或设定默认值
    }
  } else {
    formData.value.categoryName = ''; // 清空或设定默认值
  }
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ArticleVO
    if (formType.value === 'create') {
      await ArticleApi.createArticle(data)
      message.success(t('common.createSuccess'))
    } else {
      await ArticleApi.updateArticle(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: undefined,
    cover: undefined,
    summary: undefined,
    content: undefined,
    status: 0,
    recommend: 0,
    seoTitle: undefined,
    seoKeywords: undefined,
    seoDescription: undefined,
    categoryName: undefined,
    categoryId: undefined,
  }
  formRef.value?.resetFields()
}

const handleUploadSuccess = (response, file) => {
  if (response && response.data) {
    formData.value.cover = response.data;
  } else {
    ElMessage.error('上传成功，但未能获取到图片 URL');
  }
};

const beforeUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

const handleExceed = (files, fileList) => {
  ElMessage.warning(`当前选择了 ${files.length} 张图片，已上传的图片将被替换`);
  fileList.splice(0);
};
</script>

<style>
.uploaded-image {
  margin-top: 10px;
  max-width: 100%;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
